//
//  FDDiseaseSubdivideViewController.m
//  FamousDoctorOnline
//
//  Created by 张睿 on 16/7/6.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

#import "FDDiseaseSubdivideViewController.h"
#import <MJExtension.h>
#import "NetWorkTool.h"
#import "FDDiseaseSubdivideModel.h"
#import "NSString+FDSpell.h"
#import <Masonry.h>
#import "AppDelegate.h"

@interface FDDiseaseSubdivideViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
//疾病细分数组
@property (nonatomic, strong)NSArray * diseaseList;
//tableVeiw
@property (nonatomic, strong)UITableView * diseaseTableView;
//tableVeiwCell
@property (nonatomic, strong)UITableViewCell * cell;
//模糊搜索
@property (nonatomic, strong)UISearchBar *searchBar;
/** 存储模型的数组 */
@property (nonatomic, strong) NSMutableArray *storeUserDTOList;

/** 搜索数组 */
@property (nonatomic, strong) NSMutableArray *seachUserDTOList;

/** 是否在搜索状态 */
@property (nonatomic, assign) BOOL isSearchState;


@end

@implementation FDDiseaseSubdivideViewController


- (void)setDiseaseList:(NSArray *)diseaseList{
    _diseaseList = diseaseList;
    
    [self.diseaseTableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    //监测网络
    AppDelegate *appDelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if (!appDelegate.isAchieve) {
        
        [self presentAlertVC:@"⚠️网络异常，请检查是否连接网络"];
    }
}

-(void)presentAlertVC:(NSString *)str{
    
    //创建网络异常弹框
    UIAlertController *alertVC=[UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [self presentViewController:alertVC animated:YES completion:nil];
    
    UIAlertAction *identify=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:cancle];
    [alertVC addAction:identify];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建一个tableView加载到ViewController上
    [self setupTableView];
    //获取网络数据
    [self getDiseaseListWithURL:self.requestURL parmas:self.parmasDict];
    //创建Nav
    [self setupNavigationItem];
    
}

//读取网络数据
- (void)getDiseaseListWithURL:(NSString *)url parmas:(NSDictionary *)dict{
    
    NSDictionary *paramDic = @{
                               @"page_size":@15,
                               @"page":@1,
                               @"ci1_id":@1,
                               @"keyword":@""
                               };
    //请求网络数据
    [[NetWorkTool shareManager] POST_RequestWithUrlString:@"http://iosapi.itcast.cn/searchCI3List.json.php" parmas:paramDic successBloock:^(id responseObject) {
        
        //将一个字典数组转成模型数组
        self.diseaseList = [FDDiseaseSubdivideModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        NSMutableArray * nameArray = [NSMutableArray array];
        
        [self.diseaseList enumerateObjectsUsingBlock:^(FDDiseaseSubdivideModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [nameArray addObject:obj.ci3_name];
            

        }];
        for (int i = 0; i < self.diseaseList.count; i++) {
            
            FDDiseaseSubdivideModel * model = [FDDiseaseSubdivideModel new];
            
            NSString *PinYin =  [nameArray[i] transToSpell];
            
            //首字母
            NSString *FirstLetter = [nameArray[i] transToSpellFirstCase];
            
            model.namePinYin = PinYin;
            model.nameFirstLetter = FirstLetter;
            model.ci3_name = nameArray[i];
            
            [self.storeUserDTOList addObject:model];
        }
        
   } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
    
}

//创建一个tableView
- (void)setupTableView {
    
    self.diseaseTableView =
    [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    //设置代理
    self.diseaseTableView.delegate = self;
    self.diseaseTableView.dataSource = self;
    
    //添加到当前ViewController上
    [self.view addSubview:self.diseaseTableView];
}

//tableView的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_isSearchState){
 
        return self.seachUserDTOList.count;
        
//        [self.diseaseTableView reloadData];
    }else{
        return self.diseaseList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"diseaseSubdivide"];
    if (self.cell == nil) {
        
        self.cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"diseaseSubdivide"];
    }

   // 为cell赋值
    
    if (_isSearchState) {
        
       FDDiseaseSubdivideModel * model1= self.seachUserDTOList[indexPath.row];
        self.cell.textLabel.text = model1.ci3_name;
        
    }else{
        FDDiseaseSubdivideModel * model = self.diseaseList[indexPath.row];
        self.cell.textLabel.text = model.ci3_name;
    }

    return self.cell;
}

- (void)returnText:(blackBlock)block{
    
    self.returnBlock = block;
}

//点击cell返回上一个界面,返回cell.textLabel.text
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FDDiseaseSubdivideModel * model = self.diseaseList[indexPath.row];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.returnBlock) {
        self.returnBlock(model.ci3_name);
    }
    
}



- (void)viewWillDisappear:(BOOL)animated{
    [self.searchBar removeFromSuperview];
}


- (void)setupNavigationItem{
    
    self.searchBar = [[UISearchBar alloc] init];
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.searchBar.placeholder = @"请输入关键字";
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] init];
    self.navigationItem.rightBarButtonItem = item;
    
    self.navigationItem.titleView = self.searchBar;
    
    self.searchBar.delegate = self;
    
}
//模糊搜索
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    //搜索数组的长度大于0,就清空搜索数组
    if (self.seachUserDTOList.count>0) {
        
        [self.seachUserDTOList removeAllObjects];
    }
    
    //开始搜索
    NSString *key = searchText.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];
    
     NSLog(@"key = %@",key);
    //如果有输入关键词
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        //遍历模型数组,模型数组存储的就是当前所有资源的拼音信息的模型
        [self.storeUserDTOList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            FDDiseaseSubdivideModel * model = self.storeUserDTOList[idx];
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = model.ci3_name.lowercaseString;
            NSString *namePinyin = model.namePinYin.lowercaseString;
            NSString *nameFireLetter = model.nameFirstLetter.lowercaseString;
            
            //关键词在当前这个模型的名字中的的range
            NSRange rang1 = [name rangeOfString:key];
            //如果length>0,表示在模型的name中已经找到对应的key,则添加该模型()
            if (rang1.length>0) { ///比牛 -比
                
                [tempArr addObject:model];
            }else{//如果name中没有找到,那就继续到namePinyin中查找和首字母中查找
                //如果首字母包含关键词,则添加该模型
                if ([nameFireLetter containsString:key]) { //bn - b
                    
                    [tempArr addObject:model];
                    
                }else{  //ershou
                    
                    //若当前模型的首字母只含关键词的首个字符
                    
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        //如果当前模型的拼音信息中包含这个关键词
                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:model];
                        }
                    }
                }
            }
        }];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.seachUserDTOList containsObject:tempArr[idx]]) {
                
                [self.seachUserDTOList addObject:tempArr[idx]];
            }
        }];
        
        self.isSearchState = YES;
    }else{
        
        self.isSearchState = NO;
    }
    
    
    [self.diseaseTableView reloadData];

}


#pragma mark  - Lazy
- (NSMutableArray *)storeUserDTOList{
    if (_storeUserDTOList == nil) {
        _storeUserDTOList = [NSMutableArray array];
    }
    return _storeUserDTOList;
}

- (NSMutableArray *)seachUserDTOList{
    if (_seachUserDTOList == nil) {
        _seachUserDTOList = [NSMutableArray array];
    }
    return _seachUserDTOList;
}

@end
